package com.woniuxy.controller;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.woniuxy.dto.ResultServiceIn;
import com.woniuxy.pojo.Property;
import com.woniuxy.pojo.Users;
import com.woniuxy.pojo.Vendor;
import com.woniuxy.service.PropertyService;

import com.woniuxy.util.CodeUtil;
import com.woniuxy.util.MD5Util;
import com.woniuxy.util.SmsTool;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.beans.factory.annotation.Value;
import javax.servlet.http.HttpServletRequest;
import javax.sound.midi.Soundbank;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Controller
@RequestMapping("/vendor")
@CrossOrigin(allowCredentials="true",maxAge = 3600)
@PropertySource(value = "classpath:config/global.properties")
@Api(tags = "物业类")
public class PropertyController {


    @Autowired
    private PropertyService propertyService;

    @Autowired
    private RedisTemplate redisTemplate;


    //文件存储路径的根目录
    @Value("${upfile.path}")
    private String root;

    //物业登录验证
    @PostMapping("/login")
    @ResponseBody
    @ApiOperation(value = "物业登录方法")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "account",value = "账号",required = true,dataType = "String"),
            @ApiImplicitParam(name = "password",value = "密码",required = true,dataType = "String")
    })
    public Map login(String account,String password){
        Map<String,Object> map = new HashMap<>();
        if(account == null || "".equals(account) || password == null || "".equals(password)){
            map.put("code",500);
            map.put("msg","账号或密码不能为空！");
        }else {
            Property p = propertyService.findProByAccount(account);
            if (p == null){
                map.put("code",500);
                map.put("msg","账号不存在！");
            }else {
                //获取加密后的密码
                String pwd = MD5Util.md5Encrypt(account, password);
                if (!p.getPassWord().equals(pwd)){
                    map.put("code",500);
                    map.put("msg","密码错误！");
                }else {
                    if(p.getStatus() == 1){
                        map.put("code",200);
                        map.put("vid",p.getId());
                        map.put("msg","登录成功！");
                    }else {
                        if(p.getPhone() == null){
                            map.put("code",300);
                            map.put("vid",p.getId());
                            map.put("msg","调整商户注册信息完善页面");
                        }else{
                            map.put("code",403);
                            map.put("msg","账户正在审核中，请审核通过后再登录！");
                        }
                    }
                }
            }
        }
        return map;
    }

    //物业注册，验证用户名是否重复
    @PostMapping("/checkAccount")
    @ResponseBody
    @ApiOperation(value = "物业注册，验证用户名是否重复")
    @ApiImplicitParam(name = "account",value = "账号",required = true,dataType = "String")
    public Map checkAccount(String account){
        Map<String,Object> map = new HashMap();
        Property p = propertyService.findProByAccount(account);
        if(p != null){
            map.put("code",400);
            map.put("msg","用户名已被注册！");
        }else {
            map.put("code",200);
            map.put("msg","用户名可用！");
        }
        return map;
    }

    //注册发送手机验证码
    @PostMapping(value = "/sendCode")
    @ResponseBody
    @ApiOperation(value = "注册时发送手机验证码")
    @ApiImplicitParam(name = "phone",value = "手机号码",required = true,dataType = "String")
    public Map<String,Object> smsXxs(String phone, HttpServletRequest request) throws ClientException {
        Map<String,Object> map = new HashMap<>();
        //对传入的手机号码进行后端验证
        String regex = "^[1][3,4,5,7,8,9][0-9]{9}$";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(phone);
        if(!m.matches()){
            map.put("code",500);
            map.put("msg","请输入合法手机号码！");
        }else {
            // 验证码（指定长度的随机数）
            String code = CodeUtil.generateVerifyCode(6);
            String TemplateParam = "{\"code\":\""+code+"\"}";
            // 短信模板id
            String TemplateCode = "SMS_177535976";
            SendSmsResponse response = SmsTool.sendSms(phone,TemplateParam,TemplateCode);
            /*
             * map.put("verifyCode",code); map.put("phone",phone);
             */
            request.getSession().setAttribute("CodePhone",code);
            if( response.getCode().equals("OK")) {
                //短信验证码设置有效时间60秒
                redisTemplate.opsForValue().set(phone,code,60, TimeUnit.SECONDS);
                map.put("code",200);
                map.put("msg","验证码发送成功！");
            }
        }
        return map;
    }

    //物业手机注册
    @PostMapping("/register")
    @ResponseBody
    @ApiOperation(value = "物业注册")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "account",value = "手机号码",required = true,dataType = "String"),
            @ApiImplicitParam(name = "pwd",value = "密码",required = true,dataType = "String"),
            @ApiImplicitParam(name = "code",value = "验证码",required = true,dataType = "String")
    })
    public Map register(String account,String pwd,String code){
        System.out.println(account+":"+pwd+":"+code);
        Map<String,Object> map = new HashMap<>();
        //此处利用redis验证code是否过期
        String rcode = (String) redisTemplate.opsForValue().get(account);
        System.out.println(rcode+"redis中的验证码");
        //如果
        if(rcode == null){
            map.put("code",403);
            map.put("msg","验证码已失效，请重新发送！");
        }else if (!rcode.equals(code)){
            map.put("code",403);
            map.put("msg","验证码错误，请确认后重试！");
        } else {
            Property p = new Property();
            p.setAccount(account);
            String newPwd = MD5Util.md5Encrypt(account, pwd);
            p.setPassWord(newPwd);
            p.setStatus(0);
            propertyService.insertProperty(p);
            map.put("code",200);
            //讲物业注册的主键id返回，用于注册后的信息完善
            map.put("vid",p.getId());
        }
        return map;
    }


    //上传文件
    @PostMapping("/upload")
    @ResponseBody
    @ApiOperation(value = "图片上传")
    @ApiImplicitParam(name = "file",value = "MultipartFile",required = true,dataType = "MultipartFile")
    public Map upload(MultipartFile file){
        Map map = new HashMap();
        //文件名
        String fileName = new SimpleDateFormat("yyyyMMddhhmmsss").format(new Date());
        //文件的扩展名  hello.jpg
        String  ext = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        //归档
        String filePath = root+ File.separator+fileName+ext;
        try {
            file.transferTo(new File(filePath));
            Map result = new HashMap<>();
            //向客户端返回文件的路径  src==>  /carousel/img/hello.jpg
            map.put("src","../../images/"+fileName+ext);
            map.put("code",200);
            map.put("msg","上传成功!");
            return map;
        } catch (IOException e) {
            e.printStackTrace();
            map.put("code",500);
            map.put("msg","上传失败!");
            return map;
        }
    }

    //完善注册信息页面提交的数据
    @PostMapping("/perfectInfo")
    @ResponseBody
    @ApiOperation(value = "完善注册信息页面提交的数据")
    @ApiImplicitParam(name = "property",value = "Property类对象",required = true,dataType = "Property")
    public Map perfectInfo(Property property){
        Map<String,Object> map = new HashMap();
        System.out.println(property);
        //将物业完善的信息存入数据库，待管理员审核
        try {
            propertyService.updateProperty(property);
            map.put("code",200);
            map.put("msg","success");
        }catch (Exception e){
            e.printStackTrace();
            map.put("code",500);
            map.put("msg","error");
        }
        return map;
    }


    //跳转后台首页后加载当前登录人信息
    @PostMapping("/findMsgById")
    @ResponseBody
    @ApiOperation(value = "跳转后台首页后加载当前登录人信息")
    @ApiImplicitParam(name = "pid",value = "物业表id",required = true,dataType = "Long")
    public Map findMsgById(Long pid){
        Map map = new HashMap();
        Property pro = propertyService.findProById(pid);
        map.put("code",200);
        map.put("pname",pro.getCompany());
        map.put("img",pro.getHeadImg());
        map.put("pro",pro);
        return map;
    }


    //物业个人信息修改
    @PostMapping("/updateProById")
    @ResponseBody
    @ApiOperation(value = "物业个人信息修改")
    @ApiImplicitParam(name = "property",value = "Property类对象",required = true,dataType = "Property")
    public Map updateProById(Property property){
        Map<String,Object> map = new HashMap();
        System.out.println(property);
        try {
            propertyService.updateProperty(property);
            map.put("code",200);
            map.put("msg","修改成功！");
        }catch (Exception e){
            e.printStackTrace();
            map.put("code",500);
            map.put("msg","修改失败！");
        }

        return map;
    }

    //物业修改个人密码
    @PostMapping("/updatePedById")
    @ResponseBody
    @ApiOperation(value = "物业修改个人密码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "物业表id",required = true,dataType = "Long"),
            @ApiImplicitParam(name = "oldPwd",value = "旧密码",required = true,dataType = "String"),
            @ApiImplicitParam(name = "newPwd",value = "新密码",required = true,dataType = "String")
    })
    public Map updatePedById(Long id,String oldPwd,String newPwd){
        Map map = new HashMap();
        //System.out.println(id+"/"+oldPwd+"/"+newPwd);
        Property pro = propertyService.findProById(id);
        //将用户输入的旧密码加密
        String old = MD5Util.md5Encrypt(pro.getAccount(), oldPwd);
        //验证旧密码是否正确
        if (pro.getPassWord().equals(old)){
            //将用户输入的新密码进行加密
            String newPass = MD5Util.md5Encrypt(pro.getAccount(), newPwd);
            //更新密码
            propertyService.updatePassById(id,newPass);
            map.put("code",200);
            map.put("msg","修改成功！");
        }else {
            map.put("code",500);
            map.put("msg","原始密码不正确！");
        }
        return map;
    }


    //服务入驻页面请求的参数
    @GetMapping("/serviceIn")
    @ResponseBody
    @ApiOperation(value = "服务入驻页面请求的数据")
    @ApiImplicitParam(name = "id",value = "物业表id",required = true,dataType = "Long")
    public Map findServiceIn(Long id){
        //System.out.println(id+"????????????????????");
        Map<String,Object> map = new HashMap<>();
        List<ResultServiceIn> lists = propertyService.findServiceIn(id);
        //System.out.println(lists);
        map.put("code",0);
        map.put("msg","");
        map.put("count",null);
        map.put("data",lists);
        return map;
    }

    //物业取消入驻的服务
    @PostMapping("/delServiceIn")
    @ResponseBody
    @ApiOperation(value = "物业取消入驻的服务")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "物业表id",required = true,dataType = "Long"),
            @ApiImplicitParam(name = "smid",value = "服务菜单表id",required = true,dataType = "Long")
    })
    public Map delServiceIn(Long id,Long smid){
        Map<String,Object> map = new HashMap<>();
        //System.out.println(id+"?????"+smid);
        try {
            propertyService.delServiceIn(id,smid);
            map.put("code",200);
            map.put("msg","取消成功！");
        }catch (Exception e){
            e.printStackTrace();
            map.put("code",500);
            map.put("msg","取消失败！");
        }
        return map;
    }

    //物业修改入驻服务的金额
    @PostMapping("/updateServerPrice")
    @ResponseBody
    @ApiOperation(value = "物业修改入驻服务的金额")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "物业表id",required = true,dataType = "Long"),
            @ApiImplicitParam(name = "smid",value = "服务菜单表id",required = true,dataType = "Long"),
            @ApiImplicitParam(name = "price",value = "价格",required = true,dataType = "Double")
    })
    public Map updateServerPrice(Long id,Long smid,Double price){
        Map<String,Object> map = new HashMap<>();
        //System.out.println(id+"/////////"+smid+"??????"+price);
        try {
            propertyService.updateServerPrice(id,smid,price);
            map.put("code",200);
            map.put("msg","修改成功！");
        }catch (Exception e){
            e.printStackTrace();
            map.put("code",500);
            map.put("msg","修改失败！");
        }
        return map;
    }

    //查询当前物业可入驻的服务
    @GetMapping("/canBeIn")
    @ResponseBody
    @ApiOperation(value = "查询当前物业可入驻的服务")
    @ApiImplicitParam(name = "id",value = "物业表id",required = true,dataType = "Long")
    public Map canBeIn(Long id){
        Map<String,Object> map = new HashMap<>();
        List<ResultServiceIn> lists = propertyService.canBeIn(id);
        //System.out.println(lists);
        map.put("code",0);
        map.put("msg","");
        map.put("count",null);
        map.put("data",lists);
        return map;
    }

    //物业进行服务入驻
    @PostMapping("/oneServiceIn")
    @ResponseBody
    @ApiOperation(value = "物业进行服务入驻")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "物业表id",required = true,dataType = "Long"),
            @ApiImplicitParam(name = "smid",value = "服务菜单表id",required = true,dataType = "Long"),
            @ApiImplicitParam(name = "price",value = "价格",required = true,dataType = "Double")
    })
    public Map oneServiceIn(Long id,Long smid,Double price){
        Map<String,Object> map = new HashMap<>();
        try {
            propertyService.oneServiceIn(id,smid,price);
            map.put("code",200);
            map.put("msg","入驻成功！");
        }catch (Exception e){
            e.printStackTrace();
            map.put("code",500);
            map.put("msg","入驻失败！");
        }
        return map;
    }


    //业主管理界面数据
    @GetMapping("/ownerList")
    @ResponseBody
    @ApiOperation(value = "业主管理界面数据")
    @ApiImplicitParam(name = "id",value = "小区id",required = true,dataType = "Long")
    public Map ownerList(Long id){
        Map<String,Object> map = new HashMap<>();
        List<Users> lists = propertyService.ownerList(id);
        //System.out.println(lists);
        map.put("code",0);
        map.put("msg","");
        map.put("count",null);
        map.put("data",lists);
        return map;
    }

    //物业修改用户状态
    @PostMapping("/checkUserStatus")
    @ResponseBody
    @ApiOperation(value = "物业修改用户状态")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "用户id",required = true,dataType = "Long"),
            @ApiImplicitParam(name = "status",value = "状态码",required = true,dataType = "Integer")
    })
    public Map checkUserStatus(Long id,Integer status){
        Map<String,Object> map = new HashMap<>();
        try {
            propertyService.checkUserStatus(id,status);
            map.put("code",200);
            map.put("msg","修改成功！");
        }catch (Exception e){
            e.printStackTrace();
            map.put("code",500);
            map.put("msg","修改失败！");
        }
        return map;
    }

}
